package com.pay.ioopos.fragment;

import android.os.Looper;
import android.util.Log;

import com.pay.ioopos.NetworkState;
import com.pay.ioopos.R;
import com.pay.ioopos.activity.AbstractActivity;
import com.pay.ioopos.service.NetworkService;

public abstract class AbstractNetworkFragment extends AbstractErrorFragment implements NetworkState {
    private static final String TAG = AbstractNetworkFragment.class.getSimpleName();
    private Thread thread;

    @Override
    public void onDetach() {
        super.onDetach();
        if (null != thread) {
            thread.interrupt();
        }
    }

    @Override
    public final void run() {
        if (!useNetwork()) {
            executeNormal();
            return;
        }
        if (!NetworkService.isNetworkAvailable()) {
            executeNetworkInactive();
            return;
        }
        executeNetworkActive();
    }

    private void executeNetworkActive() {
        if (null != thread) {
            thread.interrupt();
        }
        thread = new Thread(() -> {
            if (null == Looper.myLooper()) {
                Looper.prepare();
            }
            try {
                execute();
            } catch (InterruptedException ignored) {

            } catch (Exception e) {
                Log.e(TAG, "execute: ", e);
                onError(e.getMessage());
            }
        });
        thread.start();
    }

    private void executeNetworkInactive() {
        String msg = getString(R.string.network_is_not_connected);
        speak(msg);
        onError(msg);
    }

    private void executeNormal() {
        try {
            execute();
        } catch (Exception e) {
            Log.e(TAG, "execute: ", e);
            onError(e.getMessage());
        }
    }

    protected final void speak(String text) {
        if (getActivity() instanceof AbstractActivity) ((AbstractActivity)getActivity()).speak(text);
    }

    protected final void speak(int textId) {
        if (getActivity() instanceof AbstractActivity) ((AbstractActivity)getActivity()).speak(getString(textId));
    }

    @Override
    public boolean useNetwork() {
        return true;
    }

    protected void execute() throws Exception {}

}
